<template>
	<view class="container">
		<!-- 状态栏 -->
		<view :class="statusBarViewClass"></view>
		<!-- 导航栏 -->
		<view class="customer-nav-view">
			<view class="customer-nav-left">
				<image class="logo-img" mode="aspectFill" :src="logo_img"></image>
			</view>
			<view class="customer-nav-center" @click="goSearchPage">
				<uni-icons type="search" color='#666666' size="18"></uni-icons>
				<text>搜索 丨 去发现</text>
			</view>
			<view class="customer-nav-right" @click="goFavoriteMovPage">
				<uni-icons type="star" color='#FF4F80' size="25"></uni-icons>
			</view>
		</view>
		<!-- 轮播图 -->
		<view class="video-swiper-view">
			<swiper class="video-swiper-container" autoplay circular :duration="1000" :interval="5000">
				<swiper-item v-for="item,index in banner_list" :key="index">
					<view class="swiper-item" @click="clickSwiperItem(item)">
						<image class="swiper-item-img" mode="aspectFit"
							:src="item.src.toLowerCase().startsWith('http')?item.src:(api.host+item.src)">
						</image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 影视类型 -->
		<view class="video-type-view" id="stkRef">
			<view v-for="item, index in video_type_list" :key="index">
				<view :class="['video-type-item', queryParams.typeId == item.id?'video-type-item-selected':'']"
					@click="switchVideoType(item.id)">
					{{ item.name }}
				</view>
			</view>
		</view>
		<!-- 最新更新 -->
		<view class="video-list-view">
			<view class="video-list-title">
				<text class="video-list-title-left">最新更新</text>
				<text class="video-list-title-right" @click="goMovList">
					<uni-icons type="right" color="#666666" size="6"></uni-icons>
				</text>
			</view>
			<view class="video-list-content" v-if="new_video_list.length > 0">
				<view class="video-list-item" v-for="item,index in new_video_list" :key="index"
					@click="goMovDetailPage(item)">
					<!-- 或者 aspectFill -->
					<image class="video-list-item-img" mode="aspectFit"
						:src="item.image.toLowerCase().startsWith('http')?item.image:(api.host+item.image)">
					</image>
					<text class="video-list-item-name"> {{item.name}} </text>
					<text class="video-list-item-other">
						<uni-dateformat :date="item.modifyTime" format="yyyy-MM-dd"></uni-dateformat> </text>
				</view>
			</view>
			<view class="video-list-content-empty" v-else>
				暂无数据
			</view>
		</view>
		<!-- 高分推荐 -->
		<view class="video-list-view">
			<view class="video-list-title">
				<text class="video-list-title-left">高分推荐</text>
				<text class="video-list-title-right" @click="goMovList">
					<uni-icons type="right" color="#666666" size="6"></uni-icons>
				</text>
			</view>
			<view class="video-list-content" v-if="recommend_video_list.length > 0">
				<view class="video-list-item" v-for="item,index in recommend_video_list" :key="index"
					@click="goMovDetailPage(item)">
					<image class="video-list-item-img" mode="aspectFit"
						:src="item.image.toLowerCase().startsWith('http')?item.image:(api.host+item.image)">
					</image>
					<text class="video-list-item-name"> {{item.name}} </text>
					<text class="video-list-item-other">
						<uni-dateformat :date="item.modifyTime" format="yyyy-MM-dd"></uni-dateformat>
					</text>
				</view>
			</view>
			<view class="video-list-content-empty" v-else>
				暂无数据
			</view>
		</view>

		<!-- 退出登陆提示窗 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="error" cancelText="取消并退出" confirmText="立即更新" title="新版本更新" :content="alertContent"
				@confirm="downloadUpdatePackage" @close="noUpdate"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref,
		nextTick
	} from 'vue'
	import {
		onPullDownRefresh,
		onPageScroll,
		onLoad
	} from '@dcloudio/uni-app'
	import api from '@/config/api'
	import request from '@/utils/request'
	import {
		showToast,
		clearUserInfo,
		getUserId,
		getUserInfo,
		getUserToken,
		setUserInfo
	} from '@/utils/utils.js'

	const logo_img = ref("/static/image/logo.png")

	const maxTop = ref(0)
	const statusBarViewClass = ref("status-bar-view-1")

	const banner_list = ref([])
	const video_type_list = ref([{
		id: 2,
		name: '电影'
	}]) // 影视类型列表
	const new_video_list = ref([])
	const recommend_video_list = ref([])
	const queryParams = ref({
		token: getUserToken(),
		typeId: 2,
		keyword: ''
	})

	const alertDialog = ref(null)
	const alertContent = ref("")
	const app_url = ref("")

	onLoad(() => {
		// 设置ip
		let curr_ip = uni.getStorageSync('curr_ip')
		if (curr_ip) {
			api.updateHost(curr_ip)
		} else if (process.env.NODE_ENV == 'development') {
			api.setDevHost()
		} else {
			api.setSysHost()
		}

		// #ifdef APP-PLUS
		// 检查更新
		plus.runtime.getProperty(plus.runtime.appid, (wgtInfo) => {
			if (wgtInfo.version) {
				uni.setStorageSync('curr_version', wgtInfo.version)
				checkForAppUpdates(wgtInfo.version)
			}
		});
		// #endif

		// 校验登陆
		let oldUser = getUserInfo()
		if (!oldUser) {
			clearUserInfo()
			refreshPageData()
			return
		}
		request.post(api.host + api.loginCheckUrl, {
			userId: oldUser.userId,
			token: oldUser.token
		}).then(result => {
			// 校验成功，更新缓存
			result.data.userId = result.data.id
			setUserInfo(result.data)
			refreshPageData()
		}).catch(() => {
			clearUserInfo()
			refreshPageData()
		})
	})

	onMounted(() => {
		// 渲染完立即记录stkRef的距离
		nextTick(() => {
			const query = uni.createSelectorQuery().in(this); // 创建查询
			query.select('#stkRef').boundingClientRect((data) => {
				if (data) {
					maxTop.value = data.top
				}
			}).exec();
		})
	})

	onPageScroll((e) => {
		// 监听stkRef距离，控制状态栏样式
		if (e.scrollTop + 5 > maxTop.value) {
			if (statusBarViewClass.value == "status-bar-view-1") {
				statusBarViewClass.value = "status-bar-view-2"
			}
		} else {
			if (statusBarViewClass.value == "status-bar-view-2") {
				statusBarViewClass.value = "status-bar-view-1"
			}
		}
	})

	// 下拉刷新
	onPullDownRefresh(() => {
		// 执行数据刷新逻辑
		refreshPageData(true)
	});

	// 刷新页面数据
	const refreshPageData = (neesStopPullDownRefresh = false) => {
		getBannerList()
		getDataList()
		// 停止下拉刷新动画
		if (neesStopPullDownRefresh) {
			uni.stopPullDownRefresh()
		}
	}

	// 切换视频类型
	const switchVideoType = (typeId) => {
		queryParams.value.typeId = typeId
		getDataList()
	}

	// 获取轮播图
	const getBannerList = () => {
		request.get(api.host + api.banerUrl, queryParams.value).then(result => {
			banner_list.value = result.data
		})
	}

	// 获取影视列表数据
	const getDataList = () => {
		request.get(api.host + api.homeUrl, queryParams.value).then(result => {
			if (result.success) {
				video_type_list.value = result.data.movieTypeList
				new_video_list.value = []
				recommend_video_list.value = []
				nextTick(() => {
					new_video_list.value = result.data.newMovieList
					recommend_video_list.value = result.data.recommendMovieList
				})
			}
		})
	}

	// 轮播图点击
	const clickSwiperItem = (item) => {
		if (item.linkType === 'ad' && item.linkURL) {
			plus.runtime.openURL(item.linkURL)
			return
		}
		if (item.linkType === 'video' && item.linkParam > 0) {
			uni.navigateTo({
				url: '/pages/mov_detail/mov_detail?movieId=' + item.linkParam + '&num=0',
			})
		}
	}

	// 前往搜索页面
	const goSearchPage = () => {
		uni.navigateTo({
			url: '/pages/mov_search/mov_search'
		})
	}

	// 前往我的收藏或者登陆
	const goFavoriteMovPage = () => {
		if (getUserId() > 0) {
			uni.navigateTo({
				url: '/pages/favorite/favorite'
			})
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}

	}

	// 前往影视库
	const goMovList = () => {
		uni.switchTab({
			url: '/pages/mov_list/mov_list'
		})
	}

	// 前往详情页面
	const goMovDetailPage = (item) => {
		uni.navigateTo({
			url: '/pages/mov_detail/mov_detail?movieId=' + item.id + '&num=0',
		})
	}

	// 比较版本号
	const compareVersion = (v1, v2) => {
		const v1Arr = v1.split('.');
		const v2Arr = v2.split('.');
		const len = Math.max(v1Arr.length, v2Arr.length);
		for (let i = 0; i < len; i++) {
			const v1Seg = parseInt(v1Arr[i] || '0');
			const v2Seg = parseInt(v2Arr[i] || '0');
			if (v1Seg > v2Seg) return 1;
			if (v1Seg < v2Seg) return -1;
		}
		return 0;
	}

	// 检查新版本
	const checkForAppUpdates = (currentVersion) => {
		request.get(api.host + api.checkVersionUrl, {
			id: 4
		}).then(result => {
			if (result.success) {
				const latestVersion = result.data.version;
				if (compareVersion(currentVersion, latestVersion) < 0) {
					app_url.value = api.host + result.data.uri
					alertContent.value = "检测到新版本 " + latestVersion + "，是否立即更新？"
					alertDialog.value.open()
				}
			}
		})
	}

	// 不更新, 退出
	const noUpdate = () => {
		plus.runtime.quit();
	}

	// 下载安装包
	const downloadUpdatePackage = () => {
		uni.downloadFile({
			url: app_url.value, // 新版本安装包的下载地址
			success: (downloadResult) => {
				if (downloadResult.statusCode === 200) {
					installUpdatePackage(downloadResult.tempFilePath)
				} else {
					showToast('下载失败，请重试')
				}
			},
			fail: () => {
				showToast('下载失败')
			}
		})
	}

	// 安装应用
	const installUpdatePackage = (tempFilePath) => {
		if (uni.getSystemInfoSync().platform === 'android') {
			// Android 平台
			// 标记是否进入安装流程
			let isInstalling = false;
			// 监听应用重新激活事件（从系统安装界面返回时触发）
			plus.globalEvent.addEventListener('resume', function() {
				if (isInstalling) {
					// 用户从安装界面返回，说明取消了安装
					isInstalling = false
					showToast('已取消安装，应用即将退出')
					setTimeout(() => plus.runtime.quit(), 1500)
				}
			});
			// 开始安装流程
			isInstalling = true;
			plus.runtime.install(
				tempFilePath, {
					force: true,
				}, () => {
					showToast('安装成功，即将重启应用')
					setTimeout(() => plus.runtime.quit(), 1500)
				}, () => {
					showToast('安装失败')
					setTimeout(() => plus.runtime.quit(), 1000)
				}
			);
		}
	}
</script>

<style lang="scss">
	@import url("index.css");
</style>